package com.initialize.appapi.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.initialize.pub.mybatis.plus.entity.Article;
import com.initialize.pub.mybatis.plus.entity.Classification;
import com.initialize.pub.mybatis.plus.service.impl.ArticleServiceImpl;
import com.initialize.pub.mybatis.plus.service.impl.ClassificationServiceImpl;
import com.initialize.pub.token.UserLoginToken;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: jane
 * Date: 2020/3/13
 * Time: 9:48 下午
 * Description:
 */
@Api(tags = "分类API")
@RestController
@CrossOrigin
@RequestMapping(value = "/classification")
public class ClassificationController {
    @Autowired
    ClassificationServiceImpl classificationService;

    @Autowired
    ArticleServiceImpl articleService;

    @ApiOperation("获取分类的数量")
    @PostMapping("/count")
    @UserLoginToken
    public R<Integer> getTheNumberOfCategories() {
        return R.ok(classificationService.count());
    }

    @ApiOperation("获取所有的分类")
    @PostMapping("/list")
    @UserLoginToken
    public R<List<Classification>> getAllTags() {
        return R.ok(classificationService.list());
    }


    @ApiOperation("根据id获取分类名称")
    @GetMapping("/id/{id}")
    @UserLoginToken
    public R<Classification> getAllTags(@PathVariable int id) {
        return R.ok(classificationService.getById(id));
    }

    @ApiOperation("获取所有的父分类")
    @GetMapping("/father")
    @UserLoginToken
    public R<List<Classification>> getParentCategory() {
        return R.ok(classificationService.list(new QueryWrapper<Classification>().eq("ccid", 0)));
    }


    @ApiOperation("删除分类(不区分单个和批量)")
    @PostMapping("/delete")
    @UserLoginToken
    public R<Boolean> delete(@RequestBody List<Integer> integers) {
        integers.remove(-1);
        //将相关的文章丢到废纸篓
//        且将类型改为其他
        integers.forEach(o -> articleService.update(Article.builder().status(0).classification(-1).build(), new QueryWrapper<Article>().eq("classification", o)));
        return R.ok(classificationService.removeByIds(integers));
    }

    @ApiOperation("更新添加一体")
    @PostMapping("/save_and_update")
    @UserLoginToken
    public R<Boolean> saveOrUpdate(@RequestBody Classification classification) {
        return R.ok(classificationService.saveOrUpdate(classification));
    }


}